import React, {useState, useEffect} from 'react';
import { Button, Form, Input, message, Modal, Upload } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import PropTypes from 'prop-types';
import { Scrollbars } from 'react-custom-scrollbars';
import classnames from 'classnames/bind';

import memo from '../../common/wrapMemo';
import Loading from '../../common/Loading';
import {formatTime} from '../../../util/util';

import style from './FeatureDetail.module.scss';

const cb = classnames.bind(style);
let editValues = {};

const {IMAGE_URL} = window.CONFIG;

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = () => resolve(reader.result);

        reader.onerror = (error) => reject(error);
});

const FeatureDetail = memo((props) => {
    const {featureLoading = false, areaUnits,visibleFields,  userInfo, fields, layerFields, featureLocation, featureDatas={}, setFeatureDetailShow, deleteFeature, saveFeature} = props;
    const {role} = userInfo.toJS();

    const [isEdit, setIsEdit] = useState(false); 
    const [delBoxShow, setDelBoxShow] = useState(false);
    const [disabled, setDisabled] = useState(true);
    const [loading, setLoading] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');       // 预览图片地址
    const [previewTitle, setPreviewTitle] = useState('');       // 预览图片标题
    const [prevImageUrl, setPrevImageUrl] = useState('');
    const [fileList, setFileList] = useState([]);  
    const [isToggle, setIsToggle] = useState(true);

    const [form] = Form.useForm();

    useEffect(() => {
        editValues = {};
        return () => {
            editValues={};
        }
    },[]);

    useEffect(() => {
        setIsEdit(false);
        if(Object.keys(featureDatas).length === 0) return;
        
        Object.keys(featureDatas).forEach(key => {
            let value = String(featureDatas[key]) || '';
            if(value.includes('T') && value.includes('00+')){
                value = formatTime(value);
            }
            if(key !== 'image'){
                form.setFieldsValue({
                    [key] : value
                });
            }
        });

        if(featureDatas['image']){
            filterImages(featureDatas['image']);
        }else{
            setFileList([]);
            setPrevImageUrl('');
        }
    },[featureDatas, layerFields]);

    // 返回要素浏览面板
    const getBack = () => {
        setIsEdit(false);
    };

    // 要素编辑内容提交
    const onFinish = (values) => {
        const {images={}, ...resetValues} = values;
        let items = {...resetValues};
        const {tempArr, imageTitles} = getImages(images);

        if(tempArr.length > 0){
            items['temp'] = tempArr.join(',');
        }

        if(imageTitles.length > 0){
            items['image'] = [prevImageUrl,...imageTitles].join(',');
        }else{
            if(prevImageUrl){
                items['image'] = prevImageUrl;
            }
        }
        saveFeature(items);
    };

    // 解析图片
    const getImages = (images) => {

        let tempArr = [];
        let imageTitles = [];
        const {fileList=[]} = images;

        fileList.forEach(item => {
            const {response} = item;
            if(response){
                const {code, data} = response;
                if(code === 200) {
                    const {temp = ''} = data;
                    temp && tempArr.push(temp);
                }
            }else{
                const {title} = item;
                title && imageTitles.push(title);
            }
        });
        return {tempArr, imageTitles};
    };

    // 图片信息提取
    const filterImages = (image) => {
        // "\\da45f2a9c83d030d\\1663384883366\\,微信图片_20220903114238.jpg"
        const imageArr = image.split(',');
        let prevUrl = ''    
        let imageList = [];
        imageArr.forEach((item,index) => {
            if(index === 0){
                prevUrl = item;
            }else{
                const list = {
                    status: 'done',
                    uid: index,
                    title: item,
                    url: `${IMAGE_URL}${prevUrl}${item}`
                };
                imageList.push(list);
            }
        });
        setPrevImageUrl(prevUrl);
        setFileList(imageList);
    };

    // 判断当前用户是否为管理员
    const isAdminRole = () => {
        if(role.roleName === '管理员'){
            return true;
        }
        return false;
    }

    // 开启编辑
    const editFeature = () => {
        setIsEdit(true);
    };

    // 要素详情面板关闭
    const closeFeatureDetailPanel = () => {
        setFeatureDetailShow(false);
    };

    // 定位到要素位置
    const location = () => {
        featureLocation();
    };
    
    const confirm = () => {
        deleteFeature();
        setDelBoxShow(false);
    };

    const cancel = () => {
        setDelBoxShow(false);
    };

    // 编辑内容变化事件
    const onValuesChange = (val) => {
        const {images = '',...restValues} = val;
        editValues = {...editValues,...restValues};

        let bool = false;
        let temps = [];

        bool = Object.keys(editValues).some(key => {
            return featureDatas[key] !== editValues[key];
        });

        if(bool) {
            setDisabled(!bool);
            return;
        }

        // 图片特殊处理
        let prevImage = "", editImageArr = [];
        if(featureDatas['image']){
            prevImage = featureDatas['image'].split(',').splice(1).join(',');
        }

        if(images){
            const {fileList} = images;
            fileList.forEach(item => {
                const {response} = item;
                if(response){
                    const {data:{temp}} = response;
                    temps.push(temp);
                }else{
                    const {title} = item;
                    editImageArr.push(title);
                }
            });
        }

        if(temps.length > 0) {
            bool = true;
            setDisabled(!bool);
            return;
        }

        const editImage = editImageArr.join(',');

        if(prevImage === editImage){
            bool =  false;
        }else{
            bool =  true;
        }

        setDisabled(!bool);
    };

    // 上传前图片校验
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
            message.error('您只能上传 JPG 或 PNG 文件!');
        }

        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isLt5M) {
            message.error('图片大小不能超过 5MB!');
        }

        return isJpgOrPng && isLt5M;
    };

    // 图片移除
    const handleRemove = (file) => {
        const index = fileList.findIndex((item) => {
            return item.uid === file.uid;
        });
        let copyFileList = JSON.parse(JSON.stringify(fileList));
        if(index > -1){
            copyFileList.splice(index, 1);
        }
        setFileList(copyFileList);
    };

    // 图片预览
    const handlePreview = async (file) => {
        // if(!file.originFileObj) return;
         
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
    
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);

        // let title = file.url;
        if(file.title){
            setPreviewTitle(file.title);
        }
    };

    // 图片上传
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
      
        if (info.file.status === 'done') {
            const {file: {response}} = info;
            const {code} = response;
            if(code === 200){
                setFileList(info.fileList);
            }
            setLoading(false);
        }
    };

    // 获取label
    const getLabel = (key) => {
        key = key.replaceAll('_','');
        let label = key ;
        if(fields[key]) {
            label = fields[key];
        }

        if(areaUnits[key]){
            label = `${label}(${areaUnits[key]})`;
        }
        return label;
    }

    // 图片详情
    const imageView = fileList.map((item,index) => {
        const {url} = item;
        return <img src={url} key={index} className={style.image}/>
    });
    
    // 要素详情编辑项
    const editFormItem = Object.keys(featureDatas).length > 0 ?
        Object.keys(featureDatas).map((key, index) => {
            if(key === 'image' || key === 'uid' || key === 'updateTime' || key === 'CODE' || key === 'code'){
                return <span key={index}></span>
            }else{
                return (
                    <Form.Item label={ getLabel(key)} name={key} key={index}>
                        <Input />
                    </Form.Item>
                );
            }
        }): null;

        const buttonItemLayout = {
            wrapperCol: {
                span: 14,
                offset: 10
            }
        };

    // 要素编辑内容
    const featureEditForm = (
        <Form
            labelCol={{ span: 7 }}
            wrapperCol={{ span: 17 }}
            form={form}
            onFinish={onFinish}
            onValuesChange={onValuesChange}
        >
            {editFormItem}
            <Form.Item label="图片" valuePropName="images" name="images">
                <Upload 
                    action="/webapi/2.0/image/upload" 
                    listType="picture-card" 
                    fileList={fileList} 
                    beforeUpload={beforeUpload} 
                    onPreview={handlePreview}
                    onRemove={handleRemove}
                    onChange={handleChange}>
                        {
                            fileList.length > 5 ? null : 
                                <div>
                                    {loading ? <LoadingOutlined /> : <PlusOutlined />}
                                    <div style={{ marginTop: 8 }}>上传</div>
                                </div>
                        }
                </Upload>
            </Form.Item>
            <Form.Item label="" {...buttonItemLayout}>
                <Button type="primary" onClick={getBack} className={style.back}>
                    返回
                </Button>
                <Button type="primary" htmlType="submit" disabled={disabled}>
                    提交改动
                </Button>
            </Form.Item>
        </Form>
    );

    // 要素编辑内容
    const featureView = Object.keys(featureDatas).length > 0 ? 
        visibleFields.map((key, index) => {
            const resolveKey = key.replaceAll('_','');
            let value = featureDatas[resolveKey]? String(featureDatas[resolveKey]) : '-';

            if(value.includes('T') && value.includes('00+')){
                value = formatTime(value);
            }

            const itemLeftClassName = cb({
                itemSpan: true,
                itemLeft: key.length >= String(value).length
            });
            const rightLeftClassName = cb({
                itemSpan: true,
                itemRight: key.length < String(value).length
            });
            return (
                <div className={style.featureViewBox} key={index}>
                    <div className={style.item}>
                        <span className={itemLeftClassName}>{getLabel(key)}</span>
                        <span className={rightLeftClassName}>{value}</span>
                    </div>
                </div>
            )
        }): null;
    
    // 图片内容
    return (
        <>
            <div className={style.featureDetail}>
                <div className={style.header}>
                    <span>{featureDatas['uid'] || ''}</span>
                    <div>
                        <span className={style.iconBox}>
                            {
                                isToggle ? <i className="iconfont icon-toggle-top" onClick={() => setIsToggle(!isToggle)}></i>:
                                <i className="iconfont icon-toggle-bottom" onClick={() => setIsToggle(!isToggle)}></i>
                            }
                        </span>
                        <i className="iconfont icon-close" onClick={closeFeatureDetailPanel}></i>
                    </div>
                </div>  
                {
                    isToggle && 
                    <div className={style.content}>
                    {
                        featureLoading ? <Loading /> : 
                        <div className={style.featureContent}>
                            {
                                !isEdit && 
                                <div className={style.btns}>
                                    <span onClick={location}>移动到此处</span>   
                                    {/* <span onClick={upload}>图片上传</span>  */}
                                    <span onClick={editFeature}>编辑属性</span>  
                                    { 
                                        isAdminRole() && <span onClick={() => setDelBoxShow(true)}>删除图斑</span>
                                    }           
                                </div>   
                            } 
                            
                            <div className={style.featureTitle}>
                                <span>字段信息</span>
                            </div>
                            <div className={style.crossline}></div>
                            <div className={style.featureInfo}>
                                <Scrollbars autoHeight autoHeightMin={0} autoHeightMax={`calc(100vh - 300px)`} style={{overflowX: 'hidden'}}>
                                    {
                                        isEdit ? featureEditForm : featureView
                                    }
                                    {
                                        !isEdit && fileList.length > 0 && 
                                        <div className={style.viewImageBox}>
                                            <span className={style.imageTitle}>图片:</span>
                                            <span className={style.images}>
                                                {imageView}
                                            </span>
                                        </div>
                                    }
                                </Scrollbars>  
                            </div>
                        </div>
                    }
                    
                    </div>
                }
                
            </div> 
            {
                delBoxShow && 
                <div className={style.delBox}>
                    <div className={style.header} >
                        <i className='iconfont icon-close' onClick={cancel}></i>
                    </div>
                    <div className={style.content}>
                        <i className='iconfont icon-warning'></i>
                        <span>是否删除数据?</span>
                    </div>
                    <div className={style.delBtn} onClick={confirm}><span>删除</span></div>
                </div>
            }
            <Modal visible={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img
                    alt="example"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
        </>
    )
});

FeatureDetail.propTypes = {
    userInfo: PropTypes.object,
    fields: PropTypes.object,
    featureLoading: PropTypes.bool,
    featureDatas: PropTypes.object,
    setFeatureDetailShow: PropTypes.func,
    deleteFeature: PropTypes.func,
    saveFeature: PropTypes.func,
    featureLocation: PropTypes.func,
    layerFields: PropTypes.object,
    areaUnits: PropTypes.object,
    visibleFields: PropTypes.array
};

export default FeatureDetail;